import {ADD_TODO, DEL_TODO, CLEAR_COMPLETED_TODO, CHANGE_TODO, TOGGLE_TODO, TOGGLE_ALL} from '../action-types'

let todo_count = 0;
export const todos = (state = [], action) => {
    switch (action.type) {
        case ADD_TODO:
            return [
                {
                    id: todo_count++,
                    text: action.text,
                    completed: false
                },
                ...state,
            ];
        case DEL_TODO:
            return state.filter((todo) => (todo.id !== action.id));
        case CLEAR_COMPLETED_TODO:
            return state.filter(todo => {
                return !todo.completed
            });
        case CHANGE_TODO:
            return state.map((todo) => {
                if (todo.id === action.id) {
                    return Object.assign({}, todo, {
                        text: action.text
                    })
                }
                return todo;
            });
        case TOGGLE_TODO:
            return state.map((todo) => {
                if (todo.id === action.id) {
                    return Object.assign({}, todo, {
                        completed: !todo.completed
                    });
                }
                return todo;
            });
        case TOGGLE_ALL:
            return state.map((todo) => {
                if (todo.completed !== action.toggle) {
                    return Object.assign({}, todo, {
                        completed: action.toggle
                    })
                }
                return todo
            });
        default:
            return state;
    }
};